import axios from 'axios';
import * as constants from './constants';

const changeLogin = () => ({
  type: constants.CHANGE_LOGIN,
  login: localStorage.getItem("login")
});

const storeId = (data) => ({
  type: constants.STORE_ID_USERNAME,
  id: localStorage.getItem("id")
})

export const logout = () => ({
  type: constants.LOGOUT,
  login: false
})

export const login = (username, password) => {
  return (dispatch) => {
    axios.post('http://localhost:9080/sys/login?username='+username+'&password='+password)
      .then((res) => {
        // 将access_token 和 refresh_token写入本地
        console.log(res.data);
        localStorage.setItem("access_token", res.data.access_token);
        localStorage.setItem("refresh_token", res.data.refresh_token);
        localStorage.setItem("login", true);
        localStorage.setItem("id", res.data.loginUser.id);
        dispatch(changeLogin());
        // axios.get('http://localhost:9080/users-anon/internal?username='+username, {
        //   headers: {
        //     'Authorization': "Bearer " + localStorage.getItem("access_token")
        //   }
        // }).then((res) => {
        //   localStorage.setItem("id", res.data.id);
        //   dispatch(storeId());
        // }).catch(() => {
        //   console.log('error');
        // })
      }).catch(()=>{
        alert('登录失败！');
      })
  }
}